<template>
  <div>
    <h1>{{ 'app详情' }}</h1>
    <el-divider></el-divider>
    <div class="info-box">
      <div>
        <img style="width:150px;height:150px" :src="launchInfo.logo" alt="" />
        <p>{{ launchInfo.appName }}</p>
      </div>

      <div style="text-align: left; flex: 2">
        <p>
          <span class="left">APP-ID：</span
          ><span class="left-main">{{ launchInfo.appId }}</span
          ><span class="right">最近上线时间：</span
          ><span>{{ launchInfo.onlineTime }}</span>
        </p>
        <p>
          <span class="left">最新版本：</span
          ><span class="left-main">{{
            `${launchInfo.version}（${launchInfo.versionNumber}）`
          }}</span
          ><span class="right">上线学校：</span
          ><span>{{ launchInfo.issueSchool }}所</span>
        </p>
      </div>
      <div>
        <el-button
          @click="
            dialogFormVisible = true
            form.appName = launchInfo.appName
            form.appId = launchInfo.appId
          "
          type="primary"
          >发布新版本</el-button
        >
        <el-button type="primary" @click="changeStatus">{{
          launchInfo.status ? '启用APP' : '停用APP'
        }}</el-button>
      </div>
    </div>
    <el-divider></el-divider>
    <h1>
      版本管理 &nbsp;&nbsp;<span style="font-size: 14px; font-weight: normal"
        >上线版本： {{ pagination.total }}个、&nbsp;上线学校：{{
          launchInfo.issueSchool
        }}所、&nbsp;&nbsp;用户数：{{ launchInfo.userCount }}台</span
      >
    </h1>
    <el-divider></el-divider>
    <div>
      <el-table :data="launchList" style="width: 100%">
        <el-table-column label="版本">
          <template slot-scope="scope">
            <span>{{
              `${scope.row.version}（${scope.row.versionNumber}）`
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上线学校">
          <template slot-scope="scope">
            <span>{{ scope.row.schoolNumber }}所</span>
          </template>
        </el-table-column>
        <el-table-column label="更新内容">
          <template slot-scope="scope">
            <pre>{{ scope.row.marks }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="是否强制更新">
          <template slot-scope="scope">
            <span>{{ scope.row.forceUpdateStatus ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近上线时间">
          <template slot-scope="scope">
            <span>{{ scope.row.onlineTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新情况">
          <template slot-scope="scope">
            <span>{{ scope.row.updateUser + '/' + scope.row.totalUser }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              :style="[
                { color: scope.row.status ? '#606266' : '#3E83F8' },
                { margin: 'margin: 0 5px 5px 0' }
              ]"
              size="mini"
              :disabled="launchInfo.status"
              @click="changeStatusRecord(scope.row)"
              >{{
                scope.row.status ? '已关闭，点击开启' : '已开启，点击关闭'
              }}</el-button
            >
            <el-button
              style="margin-left: 0"
              size="mini"
              :disabled="launchInfo.status || scope.row.status"
              @click="onlineStuVisibleFn(scope.$index, scope.row)"
              >版本上线</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="pagination.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="Number(pagination.total)"
      >
      </el-pagination>
    </div>
    <el-divider></el-divider>
    <h1>上线学校列表</h1>
    <el-divider></el-divider>
    <div>
      <el-form label-width="80px" :inline="true">
        <el-form-item label="学校名称">
          <el-input
            v-model="search.name"
            placeholder="请输入学校名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="schoolList" style="width: 100%">
        <el-table-column label="学校">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用版本">
          <template slot-scope="scope">
            <span>{{ scope.row.appVersion }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近更新">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewSchool(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSchoolSizeChange"
        @current-change="handleSchoolCurrentChange"
        :page-size="schoolPagination.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="Number(schoolPagination.total)"
      >
      </el-pagination>
    </div>
    <el-dialog title="版本上线" :visible.sync="onlineStuVisible">
      <online-box-stu
        :verType="2"
        v-if="$route.query.type == 3"
        @cancel="selectCancel"
        @change="selectChange"
      />
      <online-box-tec v-else @cancel="selectCancel" @change="selectChangeTec" />
    </el-dialog>
    <el-dialog
      title="发布新版本"
      :modal-append-to-body="false"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="form">
        <el-form-item label="APP名称" :label-width="formLabelWidth">
          <el-input
            :disabled="true"
            v-model="form.appName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="ID" :label-width="formLabelWidth">
          <el-input
            :disabled="true"
            v-model="form.appId"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="安装包" :label-width="formLabelWidth">
          <p style="margin: 0" v-if="fileName">{{ fileName }}</p>
          <el-upload
            action
            :http-request="importObj"
            :before-upload="beforeUploadImg"
            :show-file-list="false"
          >
            <el-button type="primary" class="u-btn">{{
              form.downloadUrl ? '重新上传' : '上传安装包'
            }}</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="版本号" :label-width="formLabelWidth">
          <el-input v-model="form.version" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="构建号" :label-width="formLabelWidth">
          <el-input
            type="number"
            v-model="form.versionNumber"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否强制更新" :label-width="formLabelWidth">
          <el-switch
            v-model="form.forceUpdateStatus"
            active-text="开"
            inactive-text="关"
            active-value="1"
            inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="Logo" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :http-request="uploadImg"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logo" :src="form.logo" class="avatar" />
            <span
              class="el-upload-list__item-delete"
              @click.stop="handleAvatarRemove()"
              v-if="form.logo"
              >x</span
            >
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="更新内容" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            v-model="form.marks"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="issueApp">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import base from '@/views/base.vue'
import {
  queyEnumByTableName,
  tableUpdate,
  downloadTemplateFile,
  importData
} from '@/api/api.js'
import {
  getAppInfo,
  getAppVersionList,
  getSchoolList,
  onlineApp,
  updateStatusApp,
  updateVersionStatus,
  issueApp
} from '@/api/launch'
import {
  adminschoollist,
  enumschoolall,
  adminimportschoolExport
} from '@/api/lcmapi.js'
import OnlineBoxStu from './components/online-box-stu.vue'
import OnlineBoxTec from './components/online-box-tec.vue'
import { ossUpload } from '@/api/api.js'
export default {
  name: 'launch-manage',
  data () {
    return {
      fileName: '',
      url: '',
      onlineStuVisible: false,
      dialogFormVisible: false,
      form: {
        remark: '',
        versionNumber: '',
        version: '',
        downloadUrl: '',
        appName: '',
        appId: '',
        logo: ''
      },
      formLabelWidth: '120px',
      search: {
        name: ''
      },
      multipleSelection: [],
      selectArr: {
        schoolType: [], // 学校性质
        level: [], // 学校等级
        studentScale: [], // 学生规模
        isOpen: [], // 状态
        coverageGrade: [] // 覆盖年级
      },
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      schoolPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      mode: '',
      addSchoolDialog: false,
      salesOperationDialog: false,
      list: [],
      launchInfo: {},
      launchList: [],
      schoolList: [],
      selectLaunch: null
    }
  },
  components: {
    OnlineBoxStu,
    OnlineBoxTec
  },
  activated () {
    this.$store.dispatch('common/saveRegion')
    this.search.area = []
    this.search.area[0] = 330000
    this.search.name = ''
    this.getDataList('', '', '', '')
    this.queyEnumByTableName()
  },
  computed: {
    regions () {
      return this.$store.state.common.regions
    }
  },
  methods: {
    handleAvatarRemove () {
      this.form.logo = ''
    },
    async issueApp () {
      const res = await issueApp({
        ...this.form,
        id: this.launchInfo.id,
        type: this.$route.query.type == 3 ? 1 : 2
      })
      this.$message[res[0] ? 'error' : 'success'](
        res[0] ? '操作失败' : '操作成功'
      )
      const launchList = await getAppVersionList({
        page: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        id: this.$route.query.id
      })
      this.launchList = launchList[1].data
      this.dialogFormVisible = false
    },
    selectCancel () {
      this.onlineStuVisible = false
    },
    onlineStuVisibleFn (index, record) {
      console.log(index, record)
      this.selectLaunch = record.id
      this.onlineStuVisible = true
    },
    async selectChangeTec (val) {
      let classList = []
      for (let index = 0; index < val.length; index++) {
        const element = val[index]
        for (let i = 0; i < element.checkedData.length; i++) {
          const classId = element.checkedData[i]
          classList.push({
            teacherId: classId,
            schoolId: element.schoolId
          })
        }
      }
      if (!classList.length) {
        this.$message.error('教师不能为空')
      } else {
        const updateRes = await onlineApp([
          { classesLists: classList, appVersionId: this.selectLaunch }
        ])
        if (updateRes[0]) {
          this.$message.error(updateRes[1].message)
        } else {
          this.$message.success('上线成功')
          this.selectLaunch = null
          this.onlineStuVisible = false
          const launchList = await getAppVersionList({
            page: this.pagination.pageNum,
            pageSize: this.pagination.pageSize,
            id: this.$route.query.id
          })
          this.launchList = launchList[1].data
        }
      }
      console.log(val)
    },
    async selectChange (val) {
      let classList = []
      for (let index = 0; index < val.length; index++) {
        const element = val[index]
        for (let i = 0; i < element.gradeList.length; i++) {
          const res = element.gradeList[i]
          for (let c = 0; c < res.checkedData.length; c++) {
            const classId = res.checkedData[c]
            classList.push({
              classesId: classId,
              gradeId: res.gradeId,
              schoolId: res.schoolId
            })
          }
        }
      }
      if (!classList.length) {
        this.$message.error('班级不能为空')
      } else {
        const updateRes = await onlineApp([
          { classesLists: classList, appVersionId: this.selectLaunch }
        ])
        if (updateRes[0]) {
          console.log(updateRes[1])
          this.$message.error(updateRes[1].message)
        } else {
          this.$message.success('上线成功')
          this.selectLaunch = null
          this.onlineStuVisible = false
          const launchList = await getAppVersionList({
            page: this.pagination.pageNum,
            pageSize: this.pagination.pageSize,
            id: this.$route.query.id
          })
          this.launchList = launchList[1].data
        }
      }
      console.log(val)
    },
    async handleSchoolSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.schoolPagination.pageSize = val
      const schoolList = await getSchoolList({
        page: this.schoolPagination.pageNum,
        pageSize: this.schoolPagination.pageSize,
        type: this.$route.query.type,
        appId: this.$route.query.id
      })
      this.schoolList = schoolList[1].data
      this.schoolPagination.total = Number(schoolList[1].total)
    },
    async handleSchoolCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.schoolPagination.pageNum = val
      const schoolList = await getSchoolList({
        page: this.schoolPagination.pageNum,
        pageSize: this.schoolPagination.pageSize,
        type: this.$route.query.type,
        appId: this.$route.query.id
      })
      this.schoolList = schoolList[1].data
      this.schoolPagination.total = Number(schoolList[1].total)
    },
    async getDataList (nurseryGrade, juniorGrade, middleGrade, highGrade) {
      const launchInfo = await getAppInfo({
        id: this.$route.query.id
      })
      console.log('launchInfo', launchInfo)
      const launchList = await getAppVersionList({
        page: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        id: this.$route.query.id
      })
      const schoolList = await getSchoolList({
        page: this.schoolPagination.pageNum,
        pageSize: this.schoolPagination.pageSize,
        type: this.$route.query.type,
        appId: this.$route.query.id,
        schoolName: this.search.name
      })
      this.launchInfo = launchInfo[1].data
      this.launchList = launchList[1].data
      this.schoolList = schoolList[1].data
      this.pagination.total = Number(launchList[1].total)
      this.schoolPagination.total = Number(schoolList[1].total)
    },
    // 获取枚举
    async queyEnumByTableName () {
      // 获取学校的枚举接口
      let selectArr = {
        schoolType: [], // 学校性质
        level: [], // 学校等级
        studentScale: [], // 学生规模
        isOpen: [], // 状态
        coverageGrade: [] // 覆盖年级
      }
      let enumschoolallRes = await enumschoolall({})
      if (enumschoolallRes[0]) {
        return
      }
      this.selectArr = enumschoolallRes[1].data
      this.selectArr.level = [
        {
          label: 'A',
          value: 1
        },
        {
          label: 'B',
          value: 2
        },
        {
          label: 'C',
          value: 3
        }
      ]
      this.selectArr.coverageGrade = [
        {
          label: '幼儿园',
          value: 1
        },
        {
          label: '小学',
          value: 2
        },
        {
          label: '初中',
          value: 3
        },
        {
          label: '高中',
          value: 4
        }
      ]
    },
    onSubmit () {
      this.pagination.pageNum = 1
      if (this.search.school && this.search.school.length) {
        this.getInit()
      } else {
        this.getDataList('', '', '', '')
      }
    },
    getInit () {
      let nurseryGrade = 0,
        juniorGrade = 0,
        middleGrade = 0,
        highGrade = 0
      this.selectArr.coverageGrade.forEach(item => {
        this.search.school.forEach(ele => {
          if (ele === item.value) {
            if (item.label === '幼儿园') {
              nurseryGrade = 1
            } else if (item.label === '小学') {
              juniorGrade = 1
            } else if (item.label === '初中') {
              middleGrade = 1
            } else if (item.label === '高中') {
              highGrade = 1
            }
          }
        })
      })
      this.getDataList(nurseryGrade, juniorGrade, middleGrade, highGrade)
    },
    // 批量导入
    async importObj (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'APK')
      if (res[0]) {
        return
      }
      this.form.downloadUrl = res[1].data.url
      this.fileName = res[1].data.fileName
      // this.$ref.uploadExl.clearFiles();
    },
    // 上传封面前验证
    beforeUploadImg (file) {
      console.log('file.type', file.type)
      const isExcel = file.type === 'application/vnd.android.package-archive'
      const isLt100M = file.size / 1024 / 1024 < 200
      if (!isExcel || !~file.name.indexOf('.apk')) {
        this.$message.error('上传的文件只能是 apk 格式!')
      }
      if (!isLt100M) {
        this.$message.error('上传的文件大小不能超过 200MB!')
      }
      return isExcel && isLt100M
    },
    async uploadImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'Launch')
      if (res[0]) {
        return
      }
      this.form.logo = res[1].data.url
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async handleCurrentChange (val) {
      this.pagination.pageNum = val
      const launchList = await getAppVersionList({
        page: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        id: this.$route.query.id
      })
      this.launchList = launchList[1].data
      this.pagination.total = launchList[1].total
    },
    async handleSizeChange (val) {
      this.pagination.pageSize = val
      const launchList = await getAppVersionList({
        page: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        id: this.$route.query.id
      })
      this.launchList = launchList[1].data
      this.pagination.total = launchList[1].total
    },
    async changeStatusRecord (record) {
      this.$confirm(
        record.status
          ? `确定开启  ${this.launchInfo.appName}:${record.version}（${record.versionNumber}）  APP？`
          : `关闭后该APP无法使用，确定关闭  ${this.launchInfo.appName}:${record.version}（${record.versionNumber}）  APP？`,
        record.status ? '开启' : '关闭',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          const res = await updateVersionStatus({
            id: record.id,
            status: record.status ? 0 : 1
          })
          if (res[0]) {
            this.$message({
              type: 'error',
              message: '操作失败!'
            })
          } else {
            const data = await getAppVersionList({
              page: this.pagination.pageNum,
              pageSize: this.pagination.pageSize,
              id: this.$route.query.id
            })
            this.launchList = data[1].data
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          }
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '操作成功!'
          // });
        })
    },
    async changeStatus () {
      this.$confirm(
        this.launchInfo.status
          ? `确定开启  ${this.launchInfo.appName}  APP？`
          : `关闭后该APP无法使用，确定关闭  ${this.launchInfo.appName}  APP？`,
        this.launchInfo.status ? '开启' : '关闭',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          const res = await updateStatusApp({
            id: this.launchInfo.id,
            status: this.launchInfo.status ? 0 : 1
          })
          if (res[0]) {
            this.$message({
              type: 'error',
              message: '操作失败!'
            })
          } else {
            const launchInfo = await getAppInfo({
              id: this.$route.query.id
            })
            this.launchInfo = launchInfo[1].data
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          }
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '操作成功!'
          // });
        })
    },
    viewSchool (row) {
      this.$router.push({
        name: 'launch-school-detail',
        query: { id: row.schoolId }
      })
    },
    viewApp (row) {
      this.$router.push({
        name: 'launch-app'
        // params: { id: row.id },
      })
    }
  }
}
</script>
<style scoped>
.select-box-left {
  float: left;
}
.info-box {
  display: flex;
  text-align: center;
}
.left {
  display: inline-block;
  width: 70px;
  text-align: left;
}
.left-main {
  width: 180px;
  display: inline-block;
  word-break: break-all;
  vertical-align: text-top;
}
.right {
  display: inline-block;
  width: 100px;
  text-align: left;
}
.info-box div {
  flex: 1;
}
.u-btn-box {
  display: flex;
}
.u-btn {
  font-size: 12px;
}
</style>
